# -*-coding:utf-8-*-
import re

from django.contrib.auth.backends import ModelBackend

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'token': token,
        'user_id':user.id,
        'username':user.username
    }

class UsernameMobileAuthorBackend(ModelBackend):
    """
    自定义用户名或手机号认证
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        验证用户名或手机号,返回用户对象
        :param request:
        :param username:
        :param password:
        :param kwargs:
        :return:
        """
        try:
            if re.match(r"1[3-9]\d{9}$", username):
                user = User.objects.get(mobile=username)
            else:
                user=User.objects.get(username=username)
        except:
            user = None
        # 判断密码.使用django的用户模块自带的方法
        if user is not None and user.check_password(password):
            return user